<template>
  <div style="height: 100%;">
    <el-row :gutter="20">
      <el-col :span="11">
        <el-form :inline="true">
            <el-form-item label="搜索:">
                <el-input
                v-model="keywords"
                placeholder="请输入工号或者姓名"
                ></el-input>
            </el-form-item>
            <el-form-item>
              <el-select v-model="depId" filterable placeholder="请选择学院">
                  <el-option
                    v-for="item in depOptions"
                    :key="item.depId"
                    :label="item.depName"
                    :value="item.depId">
                  </el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="searchResource()">查找</el-button>
            </el-form-item>

        </el-form>
      </el-col>
      <el-col :span="2">
      <p></p>
      </el-col>
      <el-col :span="11">
        专家标签：
        <el-select v-model="lAbelId" filterable placeholder="请选择专家标签">
            <el-option
              v-for="item in options"
              :key="item.labelId"
              :label="item.labelName"
              :value="item.labelId">
            </el-option>
          </el-select>
      </el-col>
    </el-row>

    <el-row :gutter="20" type="flex">
        <el-col :span="11">
            <h2>可选教师名单</h2>
            <el-table
                :header-cell-style="{background:'#eef1f6',color:'#606266','text-align':'center'}"
                ref="staffTable"
                :key="tableKey"
                :data="showTable"
                :row-key="getRowKey"
                border
                fit
                highlight-current-row
                @selection-change="handleStaffChange"
            >
                <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
                <el-table-column label="工号" align="center">
                  <template slot-scope="scope">
                    <span>{{ scope.row.gh }}</span>
                  </template>
                </el-table-column>

                <el-table-column label="部门" align="center">
                  <template slot-scope="scope">
                    <span>{{ scope.row.bm }}</span>
                  </template>
                </el-table-column>

                <el-table-column label="姓名" align="center">
                  <template slot-scope="scope">
                    <span>{{ scope.row.xm }}</span>
                  </template>
                </el-table-column>
            </el-table>
            <div class="resource-page">
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :page-sizes="[5,10, 15]"
                :page-size="pagesize"
                :pager-count="7"
                layout=" prev, pager, next,sizes, jumper"
                :total="filterDataShow.length"
              >
              </el-pagination>
            </div>
        </el-col>
        <el-col :span="2" style="text-align:center;">
          <div style="position: relative;top:50%;transform:translateY(-50%);">
            <div>
              <el-button
                  @click="addStaff"
                  type="primary"
                  :disabled="!staffData.length"
                  icon="el-icon-arrow-right"
                  circle
              ></el-button>
            </div>
            <el-button
                @click="removeStaff"
                type="primary"
                :disabled="!selectedStaffData.length"
                icon="el-icon-arrow-left"
                circle
                style="margin-left: 0;margin-top: 10px;"
            ></el-button>
            </div>
        </el-col>
        <el-col :span="11">
          <h2>专家名单</h2>
            <el-table
                ref="selectedStaffTable"
                :key="tableKey"
                :row-key="getRowKey"
                :data="showTableRight"
                border
                fit
                highlight-current-row
                :header-cell-style="{background:'#eef1f6',color:'#606266','text-align':'center'}"
                @selection-change="handleSelectedStaffChange"
              >
                <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
                <el-table-column label="工号" align="center">
                  <template slot-scope="scope">
                    <span>{{ scope.row.gh }}</span>
                  </template>
                </el-table-column>

                <el-table-column label="部门" align="center">
                  <template slot-scope="scope">
                    <span>{{ scope.row.bm }}</span>
                  </template>
                </el-table-column>

                <el-table-column label="姓名" align="center">
                  <template slot-scope="scope">
                    <span>{{ scope.row.xm }}</span>
                  </template>
                </el-table-column>
            </el-table>
            <div class="resource-page">
              <el-pagination
                @size-change="handleSizeRightChange"
                @current-change="handleCurrentRightChange"
                :page-sizes="[5,10, 15]"
                :page-size="rightPagesize"
                :pager-count="7"
                layout=" prev, pager, next,sizes, jumper"
                :total="selectedStaffList.length"
              >
              </el-pagination>
            </div>
        </el-col>
    </el-row>

  </div>


</template>
<script>
  export default{
    created() {
      this.getAlldeparment()
      this.getAllteacher()
      this.getAllLabels()
      this.getAllExpertAxios()
    },
    mounted() {
    },
    data() {
      return {
        filterDataShow: [], //储存符合条件的数据-
        keywords: "",
        pagesize: 10,
        currentPage: 1,
        rightPagesize: 10,
        rightCurrentPage: 1,
        listLoading: true,
        staffList: [],
        selectedStaffList: [],
        staffData: [],
        selectedStaffData: [],
        tableKey:0,
        rowKey: "rowKey",
        depId:'',
        depOptions:[{depId:'All',depName:'全部学院'}],
        options: [],
        lAbelId:'',
        allExpert:[],
        allTeacherInfo:[]
      }
    },
    computed: {
      //showTable计算属性通过slice方法计算表格当前应显示的数据
      showTable() {
        return this.filterDataShow.slice(
          (this.currentPage - 1) * this.pagesize,
          this.currentPage * this.pagesize
        );
      },
      showTableRight() {
        return this.selectedStaffList.slice(
          (this.rightCurrentPage - 1) * this.rightPagesize,
          this.rightCurrentPage * this.rightPagesize
        );
      },
    },
    watch: {
      //监听搜索框内容，当搜索框内容发生变化时调用searchResource方法
      keywords() {
        if(this.keywords==''){
          this.searchResource();
        }
      },
      depId(){
        this.showLeftByDepId()
      },
      lAbelId(){
        this.showRightByLabelId()
      }
    },
    methods: {
      showLeftByDepId(){
        this.staffList=[]
        if(this.depId=="All"){
          this.staffList=this.allTeacherInfo
        }else{
          this.staffList=this.allTeacherInfo.filter(item => item.bmbh==this.depId)
        }
        this.searchResource()
      },
      getAlldeparment(){
        this.$api.department.getSchoolDepartments().then((response)=>{
          console.log(response)
          response.data.data.departments.forEach(item=>{
            this.depOptions.push(item)
          })
        })
      },
      showRightByLabelId(){
        this.selectedStaffList=[]
        var ghs=[]
        // var tempTeacherInfos={}
        for(let i=0;i<this.allExpert.length;i++){
          if(this.lAbelId==this.allExpert[i].labelId){
            ghs.push(this.allExpert[i].gh)
          }
        }
        console.log(ghs)
        for(let i=0;i<ghs.length;i++){
          for(let j=0;j<this.allTeacherInfo.length;j++){
            if(ghs[i]==this.allTeacherInfo[j].gh){
              this.selectedStaffList.push(this.allTeacherInfo[j])
              console.log(this.selectedStaffList)
            }
          }
        }
      },
      //创建专家信息Axios
      creatExpertLabelAxios(){
        var expertLabels=[]
        console.log(this.lAbelId)
        console.log(this.staffData)
        for(let i=0;i<this.staffData.length;i++){
          this.$set(this.staffData[i],'labelId',this.lAbelId)
          expertLabels.push(this.staffData[i])
        }
        console.log(expertLabels)
        // Json格式:[     {       "elId": null,       "gh": "090008",       "labelId": 5  }   ]
        this.$api.Label.creatExpertLabel({expertLabels:JSON.stringify(expertLabels)}).then((response)=>{
          console.log(response)
          if(response.data.code==200){
            this.$message({
            	showClose: true,
            	message: "专家创建成功！",
            	type: "success",
            	center: true,
            	offset: (screen.height / 2) - 200,
              duration:1000
            })
          }else{
            this.$message({
            	showClose: true,
            	message: "专家创建失败！",
            	type: "error",
            	center: true,
            	offset: (screen.height / 2) - 200,
              duration:1000
            })
          }
          this.getAllExpertAxios()
        })
      },
      deleteExpertAxios(){
        var TempExpertLabels=[]
        for(let i=0;i<this.allExpert.length;i++){
          for(let j=0;j<this.selectedStaffData.length;j++){
            if(this.selectedStaffData[j].gh==this.allExpert[i].gh){
              TempExpertLabels.push(this.allExpert[i])
            }
          }
        }
        this.$api.Label.deleteExpertLabel({expertLabels:JSON.stringify(TempExpertLabels)}).then((response)=>{
          console.log(response)
          if(response.data.code==200){
            this.$message({
            	showClose: true,
            	message: "专家移除成功！",
            	type: "success",
            	center: true,
            	offset: (screen.height / 2) - 200,
              duration:1000
            })
          }else{
            this.$message({
            	showClose: true,
            	message: "专家移除失败！",
            	type: "error",
            	center: true,
            	offset: (screen.height / 2) - 200,
              duration:1000
            })
          }
          this.getAllExpertAxios()
        })
      },
      searchResource() {
        var numReg = /^[0-9]*$/
        var numRe = new RegExp(numReg)
        this.currentPage = 1; //将当前页设置为1，确保每次都是从第一页开始搜
        let filterKeywords = this.keywords.trim();
        let filerReasource = this.staffList.filter((item) => {
          //过滤全部数据
          if(!numRe.test(filterKeywords)){
            if (item.xm.includes(filterKeywords)) {
              return item;
            }
          }else{
            if (item.gh.includes(filterKeywords)) {
              return item;
            }
          }
        });
        this.filterDataShow = filerReasource; //将符合条件的内容赋给filterDataShow
      },
      getRowKey(row) {
        //得到当前行的key值用于保留分页前的数据
            return row.gh
          },
      handleSizeChange(psize) {
        this.pagesize = psize;
      },
      handleCurrentChange(currentPage) {
        this.currentPage = currentPage;
      },
      handleSizeRightChange(psize) {
        this.rightPagesize = psize;
      },
      handleCurrentRightChange(currentPage) {
        this.rightCurrentPage = currentPage;
      },
      getAllteacher(){
        this.$api.teacher.getAllTeacherInfo().then((response)=>{
          this.allTeacherInfo=response.data.data
          this.staffList=JSON.parse(JSON.stringify(this.allTeacherInfo))
          console.log(this.staffList)
          //过滤掉已有标签的教师
          // for(let i=0;i<this.staffList.length;i++){
          //   for(let j=0;j<this.allExpert.length;j++){
          //     if(this.staffList[i].gh==this.allExpert[j].gh){
          //       // console.log(this.staffList[i].gh)
          //       this.staffList.splice(i,1)
          //     }
          //   }
          // }
          this.searchResource()
        })
      },
        // 将左边表格选择项存入staffData中
        handleStaffChange(rows) {
          this.staffData = [];
          if (rows) {
            rows.forEach(row => {
              if (row) {
                this.staffData.push(row);
              }
            });
          }
        },
        // 左边表格选择项移到右边
        addStaff() {
          if(this.lAbelId==""){
            this.$message({
            	showClose: true,
            	message: "请选择专家标签！",
            	type: "warning",
            	center: true,
            	offset: (screen.height / 2) - 200,
              duration:1000
            })
            return
          }
          for(let j = 0;j<this.selectedStaffList.length;j++){
            for(let i = 0;i < this.staffData.length;i++){
                if(this.staffData[i].gh==this.selectedStaffList[j].gh){
                  this.$message({
                  	showClose: true,
                  	message: "该教师已添加到该分类中！",
                  	type: "warning",
                  	center: true,
                  	offset: (screen.height / 2) - 200,
                    duration:1000
                  })
                  return
                }
            }
          }
          setTimeout(() => {
            this.$refs["staffTable"].clearSelection();
            this.$refs["selectedStaffTable"].clearSelection();
          }, 0);
            this.staffData.forEach(item => {
              this.selectedStaffList.push(item);
            });
          this.creatExpertLabelAxios()
        },
        // 右边表格选择项移到左边
        removeStaff() {
          setTimeout(() => {
            this.$refs["staffTable"].clearSelection();
            this.$refs["selectedStaffTable"].clearSelection();
          }, 0);
          for (let i = 0; i < this.selectedStaffList.length; i++) {
            for (let j = 0; j < this.selectedStaffData.length; j++) {
              if (
                this.selectedStaffList[i] &&
                this.selectedStaffData[j] &&
                this.selectedStaffList[i].gh === this.selectedStaffData[j].gh
              ) {
                this.selectedStaffList.splice(i, 1);
                const totalPage = Math.ceil((this.selectedStaffList.length) / this.rightPagesize)
                this.rightCurrentPage = this.rightCurrentPage > totalPage ? totalPage : this.rightCurrentPage
                this.rightCurrentPage = this.rightCurrentPage < 1 ? 1 : this.rightCurrentPage
              }
            }
          }
          this.deleteExpertAxios()
        },
        // 将右边表格选择项存入selectedStaffData中
        handleSelectedStaffChange(rows) {
          this.selectedStaffData = [];
          if (rows) {
            rows.forEach(row => {
              if (row) {
                this.selectedStaffData.push(row);
              }
            });
          }
        },
        getAllLabels(){
          this.$api.Label.getLabels().then((response)=>{
            this.options=response.data.data
          })
        },
        getAllExpertAxios(){
          this.$api.Label.getExpertLabels().then((response)=>{
            this.allExpert=response.data.data
          })
        }

    }
  }
</script>
